package com.lottery.material.controller.portal.article;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.competition.CompetitionInfoService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.ParameterUtil;
import com.lottery.material.util.ResponseResult;
import com.lottery.material.vo.portal.article.ArticleDeletedVo;
import com.lottery.material.vo.portal.article.ArticleUserVo;
import com.lottery.material.vo.portal.competition.CompetitionArticleVo;
import com.lottery.material.vo.portal.user.CollectArticleUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "文章查询相关接口", tags = { "文章查询相关接口" })
@Controller
@RequestMapping("/portal/article")
@Slf4j
public class ArticleInfoController extends BaseController {

    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @Autowired
    ArticleInfoService articleInfoService;

    @Autowired
    PortalUserInfoService portalUserInfoService;

    @Autowired
    CompetitionInfoService competitionInfoService;

    @ApiOperation(value="他人用户中心-文章列表接口", notes="他人用户中心-文章列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识", required = true, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "用于分页", required = true, dataType = "String")
    })
    @RequestMapping(value = "/getArticleList" ,method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getArticleList(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }
        String userId = reqParamMap.get("userId");
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"userId"));
        }
        String page = reqParamMap.get("page");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"page"));
        }

        ResponseResult x = ParameterUtil.checkSign(reqParamMap);
        if (x != null) return x;

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(reqParamMap);
        List<Map<String,Object>> articleInfo = articleInfoService.findByUserIdAndPage(paramMap);
        ArticleUserVo userVo = portalUserInfoService.findArticleUserVoByUserId(userId);
        setupArticleInfo(articleInfo, userVo);
        return ResponseResult.buildSuccess(articleInfo);
    }


    @ApiOperation(value="用户发布的文章列表接口", notes="用户发布的文章列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "访问令牌（登录的用户必传）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "queryType", value = "查询类型（1：全部；2：推广；3：收费；4：热帖）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "用于分页", required = true, dataType = "String"),
            @ApiImplicitParam(name = "promotionState", value = "推广状态，查询类型为2时必传（1：可推广；2：已推广）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "auditState", value = "审核状态，查询类型为3或4时必传（1：待审核；2：审核不通过/驳回；3：审核通过；）", required = false, dataType = "String"),
    })
    @RequestMapping(value = "/getMyArticleList" ,method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getMyArticleList(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        Map<String,Object> paramMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        ParameterUtil.checkLogin(reqParamMap,jedisClient, portalUserInfoService);

        paramMap.putAll(reqParamMap);
        String page = reqParamMap.get("page");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"page"));
        }

        String queryType = reqParamMap.get("queryType");
        if (StringUtils.isBlank(queryType)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"queryType"));
        }

        if("2".equals(queryType)){
            String promotionState = reqParamMap.get("promotionState");
            if (StringUtils.isBlank(promotionState)) {
                return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"promotionState"));
            }else{
                paramMap.put("promotionState",Integer.valueOf(promotionState));
            }
        }
        if("3".equals(queryType)||"4".equals(queryType)){
            String auditState = reqParamMap.get("auditState");
            if (StringUtils.isBlank(auditState)) {
                return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"auditState"));
            }else{
                paramMap.put("auditState",Integer.valueOf(auditState));
            }
        }

        ResponseResult x = ParameterUtil.checkSign(reqParamMap);
        if (x != null) return x;

        List<Map<String,Object>> articleInfo = articleInfoService.findByUserIdAndPage(paramMap);
        ArticleUserVo userVo = portalUserInfoService.findArticleUserVoByUserId(reqParamMap.get("userId"));
        setupArticleInfo(articleInfo, userVo);
        return ResponseResult.buildSuccess(articleInfo);
    }

    @ApiOperation(value="回收站列表接口", notes="回收站列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "访问令牌（登录的用户必传）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "queryType", value = "查询类型（1：圈务删除；2：自己删除）", required = true, dataType = "String"),
    })
    @RequestMapping(value = "/getMyDeletedArticleList" ,method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getMyDeletedArticleList(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        ParameterUtil.checkLogin(reqParamMap,jedisClient, portalUserInfoService);
        String queryType = reqParamMap.get("queryType");
        if (StringUtils.isBlank(queryType)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"queryType"));
        }

        ResponseResult x = ParameterUtil.checkSign(reqParamMap);
        if (x != null) return x;

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userId",reqParamMap.get("userId"));
        paramMap.put("queryType",Integer.valueOf(queryType));
        List<ArticleDeletedVo> deletedVos = articleInfoService.findDeletedArticleByUserId(paramMap);
        return ResponseResult.buildSuccess(deletedVos);

    }

    /**
     * 装配articleInfo
     * @Author 焦阳
     * @param articleInfo
     * @param userVo
     */
    private void setupArticleInfo(List<Map<String, Object>> articleInfo, ArticleUserVo userVo) {
        for (int i = 0; i < articleInfo.size(); i++) {
            Map<String, Object> stringObjectMap = articleInfo.get(i);
            stringObjectMap.put("author", userVo);
            List<CompetitionArticleVo> competitionArticleVos = competitionInfoService.findCompetitionArticleVoByArticleId(Integer.parseInt(stringObjectMap.get("articleId").toString()));
            stringObjectMap.put("competition", competitionArticleVos);
        }
    }

    @ApiOperation(value="已购文章列表接口", notes="已购文章列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "访问令牌（登录的用户必传）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "用于分页", required = true, dataType = "String")
    })
    @RequestMapping(value = "/getPurchasedArticleList" ,method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getPurchasedArticleList(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }
        ParameterUtil.checkLogin(reqParamMap,jedisClient, portalUserInfoService);

        String page = reqParamMap.get("page");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"page"));
        }
        ResponseResult x = ParameterUtil.checkSign(reqParamMap);
        if (x != null) return x;

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(reqParamMap);
        List<Map<String,Object>> articleInfo = articleInfoService.findPurchasedArticleByUserIdAndPage(paramMap);
        ArticleUserVo userVo = portalUserInfoService.findArticleUserVoByUserId(reqParamMap.get("userId"));
        setupArticleInfo(articleInfo, userVo);
        return ResponseResult.buildSuccess(articleInfo);
    }

    @ApiOperation(value="我的收藏列表接口", notes="我的收藏列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户唯一标识", required = true, dataType = "String"),
            @ApiImplicitParam(name = "accessToken", value = "访问令牌（登录的用户必传）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "用于分页", required = true, dataType = "String")
    })
    @RequestMapping(value = "/getCollectArticleList" ,method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getCollectArticleList(HttpServletRequest request){
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断
        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        ParameterUtil.checkLogin(reqParamMap,jedisClient, portalUserInfoService);

        String page = reqParamMap.get("page");
        if (StringUtils.isBlank(page)) {
            return ResponseResult.buildResult(ResultEnum.PARAMETER_BLANK_ERROR.getCode(), String.format(ResultEnum.PARAMETER_BLANK_ERROR.getMessage(),"page"));
        }
        ResponseResult x = ParameterUtil.checkSign(reqParamMap);
        if (x != null) return x;

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(reqParamMap);
        List<CollectArticleUserVo> articleInfo = articleInfoService.findCollectArticleByUserIdAndPage(paramMap);
        return ResponseResult.buildSuccess(articleInfo);
    }

}
